{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "> # Dataloader"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "import cv2\n",
    "import torch\n",
    "import pandas as pd\n",
    "from skimage import io\n",
    "from torch.utils.data.dataset import Dataset\n",
    "from torch.utils.data import Dataset, DataLoader\n",
    "class MyDataset(Dataset):\n",
    "    def __init__(self,**config):\n",
    "        self.root_dir = \"../input/cassava-leaf-disease-classification/test_images/\"\n",
    "        self.labels = pd.read_csv('../input/cassava-leaf-disease-classification/sample_submission.csv')\n",
    "        self.H = config['h']\n",
    "        self.W = config['w']\n",
    "\n",
    "    def __getitem__(self,idx):\n",
    "        img_name = os.path.join(self.root_dir, self.labels.iloc[idx,0])\n",
    "        img = io.imread(img_name)\n",
    "        img = cv2.resize(img, (self.H, self.W)) \n",
    "        # swap color axis because\n",
    "        # numpy image: H x W x C\n",
    "        # torch image: C X H X W\n",
    "        img = img.transpose((2, 0, 1))\n",
    "        img = torch.tensor(img,dtype=torch.float)\n",
    "        label = self.labels.iloc[idx,1]\n",
    "        label = torch.tensor(label,dtype=torch.long)\n",
    "        sample = {'image':img,'label':label}\n",
    "        return sample\n",
    "\n",
    "    def __len__(self):\n",
    "        return len(self.labels)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Test"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.metrics import classification_report\n",
    "class Test():\n",
    "    def __init__(self,**config):\n",
    "        self.results = None\n",
    "        self.csv_path = \"../input/cassava-leaf-disease-classification/sample_submission.csv\"\n",
    "        self.dataloader = config['dataloader']\n",
    "        self.model_path = config['model_path']\n",
    "        self.out_path = 'submission.csv'\n",
    "        \n",
    "    def predict(self,):\n",
    "        model = torch.load(self.model_path)\n",
    "        results = []\n",
    "        for i,batch in enumerate(self.dataloader):\n",
    "            image = batch['image']\n",
    "            pred = model(image.cuda())\n",
    "            results+=torch.max(pred.data,1)[1].cpu().detach().numpy().tolist()\n",
    "        self.results = results\n",
    "        return results\n",
    "        \n",
    "    def out(self,):\n",
    "        out = pd.read_csv(self.csv_path)\n",
    "        out['label'] = self.results\n",
    "        out.to_csv(self.out_path,index=False)\n",
    "    "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Model"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import torch.nn as nn\n",
    "\n",
    "class AlexNet(nn.Module):\n",
    "    def __init__(self, **kwargs):\n",
    "        super(AlexNet, self).__init__()\n",
    "        self.kwargs = kwargs\n",
    "        self.features = nn.Sequential(\n",
    "            nn.Conv2d(3, 64, kernel_size=11, stride=4, padding=2),\n",
    "            nn.ReLU(inplace=True),\n",
    "            nn.MaxPool2d(kernel_size=3, stride=2),\n",
    "            nn.Conv2d(64, 192, kernel_size=5, padding=2),\n",
    "            nn.ReLU(inplace=True),\n",
    "            nn.MaxPool2d(kernel_size=3, stride=2),\n",
    "            nn.Conv2d(192, 384, kernel_size=3, padding=1),\n",
    "            nn.ReLU(inplace=True),\n",
    "            nn.Conv2d(384, 256, kernel_size=3, padding=1),\n",
    "            nn.ReLU(inplace=True),\n",
    "            nn.Conv2d(256, 256, kernel_size=3, padding=1),\n",
    "            nn.ReLU(inplace=True),\n",
    "            nn.MaxPool2d(kernel_size=3, stride=2),\n",
    "        )\n",
    "        self.classifier = nn.Sequential(\n",
    "            nn.Linear(256 * 7 * 7, 4096),\n",
    "            nn.ReLU(inplace=True),\n",
    "            nn.Linear(4096, 4096),\n",
    "            nn.ReLU(inplace=True),\n",
    "            nn.Linear(4096, self.kwargs[\"num_classes\"]),\n",
    "        )\n",
    "\n",
    "    def forward(self, x):\n",
    "        x = self.features(x)\n",
    "        x = x.contiguous().view(x.size(0), 256 * 7 * 7)\n",
    "        x = self.classifier(x)\n",
    "        return x"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Main"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "testdataset = MyDataset(**model_config)\n",
    "testdataloader = DataLoader(testdataset, batch_size=1,shuffle=False) \n",
    "\n",
    "# 加载模型\n",
    "config = {\"h\": 256, \"w\": 256, num_classes: 5, \"model_path\": \"./input/\", 'dataloader':testdataloader}\n",
    "\n",
    "model = AlexNet(**config)\n",
    "model.load_state_dict(torch.load())\n",
    "\n",
    "test = Test(**config)\n",
    "test.predict()\n",
    "test.out()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "out = pd.read_csv('submission.csv')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>Unnamed: 0</th>\n",
       "      <th>image_id</th>\n",
       "      <th>label</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>0</td>\n",
       "      <td>2216849948.jpg</td>\n",
       "      <td>3</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "   Unnamed: 0        image_id  label\n",
       "0           0  2216849948.jpg      3"
      ]
     },
     "execution_count": 10,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "out"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.0"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
